import { useAppDispatch } from '@/store/hook'
import {
  patchUserProfileAction,
  UserPhotoAction
} from '@/store/reducers/profile'
import { Popup, Toast } from 'antd-mobile'
import { Fragment, useRef } from 'react'
import styles from './index.module.scss'
export type TListPop = {
  visible: boolean
  close: () => void
  type: 'photo' | 'gender'
}

export default function ListPop ({ visible, close, type }: TListPop) {
  // 获取input的file元素
  const fileRef = useRef<HTMLInputElement>(null)
  // 调用dispatch
  const dispatch = useAppDispatch()
  // 修改性别，0为男，1为女
  const patchGender = async (gender: number) => {
    await dispatch(
      patchUserProfileAction({
        gender: gender
      })
    )
    Toast.show({
      icon: 'success',
      content: '修改成功',
      afterClose: close,
      duration: 300
    })
  }

  // 更改头像
  const changePhoto = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const fd = new FormData()
    fd.append('photo', e.target.files![0])
    await dispatch(UserPhotoAction(fd))
    Toast.show({
      icon: 'success',
      content: '更换成功',
      afterClose: close,
      duration: 300
    })
  }
  return (
    <Popup visible={visible} position='bottom' onMaskClick={close}>
      <div className={styles.root}>
        <input ref={fileRef} type='file' hidden onChange={changePhoto} />
        {type === 'photo' && (
          <Fragment>
            <div className='list-item'>拍照</div>
            <div onClick={() => fileRef.current?.click()} className='list-item'>
              本地选择
            </div>
          </Fragment>
        )}
        {type === 'gender' && (
          <Fragment>
            <div onClick={() => patchGender(0)} className='list-item'>
              男
            </div>
            <div onClick={() => patchGender(1)} className='list-item'>
              女
            </div>
          </Fragment>
        )}
        <div onClick={close} className='list-item'>
          取消
        </div>
      </div>
    </Popup>
  )
}
